package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.ProjectsMapper;
import com.ruoyi.system.mapper.ScreenMapper;
import com.ruoyi.system.service.ProjectsService;
import com.ruoyi.system.util.ImportExcelUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import fr.opensagres.xdocreport.itext.extension.font.IFontProvider;
import org.apache.commons.lang3.StringUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import com.lowagie.text.Font;
import com.google.code.appengine.awt.Color;
import com.lowagie.text.pdf.BaseFont;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ProjectsServiceImpl implements ProjectsService {
    @Autowired
    private ProjectsMapper projectsMapper;
    @Autowired
    private ScreenMapper screenMapper;

    //查询项目列表
    @Override
    public List<Projects> selectProjectsList(Projects projects) {
        List<Projects> list = projectsMapper.selectProjectsList(projects);
        //根据查询业主单位与牵头单位
        for (int i = 0; i < list.size(); i++) {
            String owner = "";
            String pullhead = "";
            String desname = "";

            Projects projects1 = new Projects();
            projects1.setProId(list.get(i).getProId());
            if (null != projectsMapper.selectProjectsCon(projects1)) {
                List<Projects> con = projectsMapper.selectProjectsCon(projects1);
                for (int i1 = 0; i1 < con.size(); i1++) {
                    owner += con.get(i1).getConName() + " ";
                }
            }
            if (null != projectsMapper.selectProjectsConName(list.get(i).getProId())) {
                List<Projects> con = projectsMapper.selectProjectsConName(list.get(i).getProId());
                for (int i1 = 0; i1 < con.size(); i1++) {
                    pullhead += con.get(i1).getConName() + " ";
                }
            }
            if (null != projectsMapper.selectProjectsDesName(list.get(i).getProId())) {
                List<String> con = projectsMapper.selectProjectsDesName(list.get(i).getProId());
                for (int i1 = 0; i1 < con.size(); i1++) {
                    desname += con.get(i1) + " ";
                }
            }
            list.get(i).setDeName(desname);
            list.get(i).setConName(pullhead);
            list.get(i).setContName(owner);
        }
        return list;
    }

    @Override
    public Vague selectVague() {
        Vague vague = new Vague();
        List<String> ly = projectsMapper.selectDomain();
        List<Desk> cm = projectsMapper.selectDesk();
        List<String> qy = projectsMapper.selectDistrict();
        List<String> cy = projectsMapper.selectIndustry();
        List<String> xz = projectsMapper.selectNature();
        List<String> lb = projectsMapper.selectType();
        List<String> zh = projectsMapper.selectCommand();
        vague.setLy(ly);
        vague.setCm(cm);
        vague.setCy(cy);
        vague.setLb(lb);
        vague.setQy(qy);
        vague.setXz(xz);
        vague.setZh(zh);
        return vague;
    }

    //项目全部删除
    @Override
    public int remove(Integer proId) {
        int remove = projectsMapper.remove(proId);
        int removeContact = projectsMapper.removeContact(proId);
        int removeDesk = projectsMapper.removeDesk(proId);
        int removeFile = projectsMapper.removeFile(proId);
        int removeIssue = projectsMapper.removeIssue(proId);
        int removeMonitoring = projectsMapper.removeMonitoring(proId);
        int removeMouth = projectsMapper.removeMouth(proId);
        int removePicture = projectsMapper.removePicture(proId);
        int removeYear = projectsMapper.removeYear(proId);
        if (remove>=0&&removeContact>=0&&removeDesk>=0&&removeFile>=0&&removeIssue>=0&&removeMonitoring>=0&&removeMouth>=0&&removePicture>=0&&removeYear>=0){
            return 1;
        }
        return 0;
    }

    //修改回显
    @Override
    public Projects getPro(Long proId) {
        return projectsMapper.getPro(proId);
    }

    //项目信息回显
    @Override
    public List<Contact> getProInf(Long proId) {
        return projectsMapper.getProInf(proId);
    }

    //项目联系信息删除
    @Override
    public int removeConById(Long conId) {
        return projectsMapper.removeConById(conId);
    }

    //项目联系信息新增
    @Override
    public int addContact(Contact contact) {
        String contName = contact.getContName();
        Long contId = projectsMapper.selectContIdByName(contName);
        contact.setContId(contId);
        return projectsMapper.addContact(contact);

    }

    //返回所有业主单位类型
    @Override
    public List<ContactType> getAllCon() {
        return projectsMapper.getAllCon();
    }

    @Override//大屏标点内容ProjectContent
    public ProjectContent selectDomesticContent(String proLongitude, String proDimensionality) {
        return projectsMapper.selectDomesticContent(proLongitude, proDimensionality);
    }

    @Override
    public List<ProjectMonitoring> queryMonitoring(ProjectMonitoring monitoring) {
        return projectsMapper.queryMonitoring(monitoring);
    }

    @Override
    public int addMonitoring(ProjectMonitoring projectMonitoring) {
        Map map=new HashMap();
        map.put("mKey",projectMonitoring.getmKey());
        map.put("proId",projectMonitoring.getProId());
        if (projectsMapper.queryByKey(map)<1) {
            return projectsMapper.addMonitoring(projectMonitoring);
        } else {
            return 0;
        }
    }

    @Override
    public int delMonitoring(Long mId) {
        return projectsMapper.delMonitoring(mId);
    }

    //项目联系信息修改
    @Override
    public int updateContact(Contact contact) {
        String contName = contact.getContName();
        Long contId = projectsMapper.selectContIdByName(contName);
        contact.setContId(contId);

        return projectsMapper.updateContact(contact);
    }


    //年度信息回显
    @Override
    public List<ProYear> getProYear(Long proId) {
        List<ProYear> proYear = projectsMapper.getProYear(proId);
        for (int i = 0; i < proYear.size(); i++) {
            //获得用户id
            Long upUserId = proYear.get(i).getUpUserId();
            Long createUserId = proYear.get(i).getCreateUserId();
            //去查询用户的名字
            String upUserName = projectsMapper.selectUserNameById(upUserId);
            String createUserName = projectsMapper.selectUserNameById(createUserId);
            //手动封装到实体类
            proYear.get(i).setCreateUserName(createUserName);
            proYear.get(i).setUpUserName(upUserName);
            String mesYear = proYear.get(i).getMesYear();
            int i1 = mesYear.indexOf("-");
            proYear.get(i).setMesYear(mesYear.substring(0, i1));
        }
        return proYear;
    }
    //新增项目
    @Override
    public int insertProjects(Projects projects) {
        //  根据名字查询ID
        Long domId = projectsMapper.selectDomById(projects.getDomName());
        Long disId = projectsMapper.selectDisById(projects.getDisName());
        Long natId = projectsMapper.selectNatById(projects.getNatName());

        //  取层面id
        List<Long> desId = new ArrayList<>();
        for (int i = 0; i < projects.getDesName().size(); i++) {
            desId.add(projectsMapper.selectDesById(projects.getDesName().get(i).getDesName()));
        }

        //  判断是否为空
        if (null != projects.getTypName()) {
            Long typId = projectsMapper.selectTypById(projects.getTypName());
            projects.setTypName(String.valueOf(typId));
        }
        if (null != projects.getIndName()) {
            Long indId = projectsMapper.selectIndById(projects.getIndName());
            projects.setIndName(String.valueOf(indId));
        }
        if (null != projects.getComName()) {
            Long comId = projectsMapper.selectComById(projects.getComName());
            projects.setComName(String.valueOf(comId));
        }
        //  往对象里添加值
        projects.setDomName(String.valueOf(domId));
        projects.setDisName(String.valueOf(disId));
        projects.setNatName(String.valueOf(natId));

        //  拿到新增的ID
        int result = 0;
        //项目id和项目名称唯一
        if (projectsMapper.queryByname(projects.getProNum(), projects.getProName()) < 1) {
            //添加部门Id
            if(0==projects.getDeptId()){
                int deptId = projectsMapper.selectDept(projects.getUserId());
                projects.setDeptId(deptId);
            }
            result = projectsMapper.insertProjects(projects);
        }
        int num = 0;
        //层面中间表
        for (int i = 0; i <projects.getDesName().size(); i++) {
             projectsMapper.insertDesk(projects.getProId(),projectsMapper.selectDesById(projects.getDesName().get(i).getDesName()));
        }
        if (result >= 0 && num >= 0) {
            return 1;
        }
        return 0;
    }

    @Override
    public int updateProjects(Projects projects) {
        System.out.println(projects.getProId());
        //  根据名字查询ID
        Long domId = projectsMapper.selectDomById(projects.getDomName());
        Long disId = projectsMapper.selectDisById(projects.getDisName());
        Long natId = projectsMapper.selectNatById(projects.getNatName());

        //  取层面id
        List<Long> desId = new ArrayList<>();
        for (int i = 0; i < projects.getDesName().size(); i++) {
            desId.add(projectsMapper.selectDesById(projects.getDesName().get(i).getDesName()));
        }
        //  判断是否为空
        if (null != projects.getTypName()) {
            Long typId = projectsMapper.selectTypById(projects.getTypName());
            projects.setTypName(String.valueOf(typId));
        }
        if (null != projects.getIndName()) {
            Long indId = projectsMapper.selectIndById(projects.getIndName());
            projects.setIndName(String.valueOf(indId));
        }
        if (null != projects.getComName()) {
            Long comId = projectsMapper.selectComById(projects.getComName());
            projects.setComName(String.valueOf(comId));
        }
        //  往对象里添加值
        projects.setDomName(String.valueOf(domId));
        projects.setDisName(String.valueOf(disId));
        projects.setNatName(String.valueOf(natId));

       //修改所在部门
        if(0==projects.getDeptId()){
            int deptId = projectsMapper.selectDept(projects.getUserId());
            projects.setDeptId(deptId);
        }
        //  拿到新增的ID
        int result = projectsMapper.updateProjects(projects);
        //删除原有的pid
        int num = projectsMapper.updateDesk(projects.getProId());
        for (int i = 0; i < desId.size(); i++) {
            //新增新的中间表
            projectsMapper.insertDesk(projects.getProId(), desId.get(i));
        }
        if (result >= 0 && num >= 0) {
            return 1;
        }
        return 0;
    }

    //报表
    public HashMap<String, Object> query(Projects projects) {
        //部门
        int dept = projectsMapper.selectDept( projects.getUserId());
        projects.setDeptId(dept);
        ArrayList arrayList = new ArrayList();
        HashMap<String, Object> exl = new HashMap();
        List<Nature> natures = projectsMapper.queryNature();
        exl.put("year", projects.getMouYear());
        for (int i = 0; i < natures.size(); i++) {
            HashMap map = new HashMap();
            exl.put("Invest" + i, projectsMapper.queryInvestBynatName(natures.get(i).getNatName(), projects.getDeptId()));
            exl.put("InvestGoal" + i, projectsMapper.queryInvestGoalBynatName(natures.get(i).getNatName(), projects.getDeptId()));
            if (projectsMapper.queryInvestBynatName(natures.get(i).getNatName(), projects.getDeptId()) == null)
                exl.put("Invest" + i, 0);
            if (projectsMapper.queryInvestGoalBynatName(natures.get(i).getNatName(),projects.getDeptId()) == null)
                exl.put("InvestGoal" + i, 0);
            exl.put("sum" + i, projectsMapper.querycountBynatName(natures.get(i).getNatName(),projects.getDeptId()));
        }
        //投资等级及项目数量
        HashMap map1 = new HashMap();
//        亿
        exl.put("Billion", projectsMapper.Billion());
        //百万
        exl.put("Million", projectsMapper.Million());
        //千万
        exl.put("TenMillion", projectsMapper.TenMillion());
        //百万以下
        exl.put("UnderMillion", projectsMapper.UnderMillion());
        //完成进度及项目数
        proStage proStage1 = new proStage();
        proStage1.setStage(25);
        HashMap<String, Object> map = new HashMap<>();
        map.put("start", 0);
        map.put("end", 25);
        map.put("userId",projects.getDeptId());
        int a = projectsMapper.selectProNum(map);
        exl.put("Num1", a);

        map.put("start", 25);
        map.put("end", 50);
        exl.put("Num2", projectsMapper.selectProNum(map));

        map.put("start", 50);
        map.put("end", 75);
        exl.put("Num3", projectsMapper.selectProNum(map));

        map.put("start", 75);
        map.put("end", 100);
        exl.put("Num4", projectsMapper.selectProNum(map));
//        周期数
        exl.put("plan1", projectsMapper.selectplan(0, projects.getDeptId()));
        exl.put("plan2", projectsMapper.selectplan(1, projects.getDeptId()));
        exl.put("sum", projectsMapper.sum(dept));

        return exl;
    }

    //导入
    public int importExcel(MultipartFile file,String userId) {
        // poi_xlsx.xlsx
        String fileName = file.getName();
        List<String[]> dataList = null;
        String headData = null;
        Workbook workbook = null;
        String dateFormat = "yyyy-MM-dd";
        boolean t = true;
        int a = 0;
        try {
        //部门
        int dept = projectsMapper.selectDept(userId);
            workbook = new XSSFWorkbook(file.getInputStream());
            if (workbook != null) {
                headData = ImportExcelUtil.getExcelHeadData(workbook);
                dataList = ImportExcelUtil.getExcelData(workbook, 1, 2, dateFormat);
            }
            //拿到数据进行数据库操作
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
            Map map = new HashMap();
            for (int j = 1; j < dataList.size(); j++) {
                Projects entity = new Projects();
                String[] strings = dataList.get(j);
                for (int i = 0; i < 14; i++) {
                    String cellValue = dataList.get(j)[i] + "";
                    if (!"null".equals(cellValue)) {
                        t = true;
                        switch (i) {
                            case 0:
                                entity.setProNum(cellValue);
                                if ("null".equals(cellValue)) continue;
                                break;
                            case 1:
                                entity.setProName(cellValue);
                                break;
                            case 2:
                                entity.setProContent(cellValue);
                                break;
                            case 3:
                                entity.setNatName(cellValue);
                                break;
                            case 4:
                                entity.setProInvest(Double.valueOf(cellValue));
                                break;
                            case 5:
                                entity.setProIssue(cellValue);
                                break;
                            case 6:
                                entity.setProStrdate(sdf.parse(cellValue));
                                break;
                            case 7:
                                entity.setProEnddate(sdf.parse(cellValue));
                                break;
                            case 8:
                                entity.setDomName(cellValue);
                                break;
                            case 9:
                                break;
                            case 10:
                                String[] Str = Convert.toStrArray(cellValue);
                                List<Desk> desName= new ArrayList<>();
                                for (int k = 0; k <Str.length; k++) {
                                    Desk desk= new Desk();
                                    desk.setDesName(Str[k]);
                                    desName.add(desk);
                                }
                                entity.setDesName(desName);
                                break;
                            case 11:
                                entity.setComName(cellValue);
                                break;
                            case 12:
                                entity.setTypName(cellValue);
                                break;
                            case 13:
                                entity.setIndName(cellValue);
                                break;
                            default:
                                break;
                        }
                    }
                }
                if (t) {
                    entity.setUserId(userId);
                    entity.setDeptId(dept);
                    a += insertProjects(entity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return a;
    }

    //查询是否为政府
    @Override
    public int selectDeptId(String userId) {
        int deptId = projectsMapper.selectDept(userId);
        //判断是否为管理员
        if (deptId!=-1){
            return projectsMapper.selectDeptId(deptId);
        }
        return 0;
    }
    @Override
    public int selectDept(String userId) {
        return projectsMapper.selectDept(userId);
    }

    @Override
    public List<ProjectMonitoring> selectYsyCamerasselfList(YsyCamerasself ysyCamerasself) {
        return projectsMapper.selectYsyCamerasselfList(ysyCamerasself);
    }

    @Override
    public int addMonitoring2(Long proId, Long id) {
        Map map =new HashMap();
        map.put("proId",proId);
        map.put("id",id);
        if(projectsMapper.sumMonitoring2(map)<=0) {
            return projectsMapper.addMonitoring2(map);
        }else{
            return 0;
        }
    }
    @Override
    public int delMonitoring2(Long proId, Long id) {
        Map map =new HashMap();
        map.put("proId",proId);
        map.put("id",id);
        return projectsMapper.delMonitoring2(map);
    }

    @Override
    public List<YsyCamerasself> querycamerabyareaid(YsyCamerasself ysyCamerasself) {
        return projectsMapper.querycamerabyareaid(ysyCamerasself);
    }
    @Override
    public List<YsyCamerasself> querycamerabyproId(Long proId) {
        return projectsMapper.querycamerabyproId(proId);
    }

}
